package com.example.module_motorcircle.publish.viewmodel

import android.util.Log
import com.example.lib_common.base.BaseViewModel
import com.example.lib_common.state.UIState
import com.example.lib_net.model.api.ImgItem
import com.example.module_motorcircle.publish.model.PublishPostRequestModel
import com.example.module_motorcircle.publish.repository.PostPublishRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.File
import javax.inject.Inject

/**
 * @author yaotianxue
 * @description
 * @date 2025/2/17
 */
@HiltViewModel
class PostPublishViewModel @Inject constructor(val repository: PostPublishRepository):BaseViewModel() {
    //帖子内容
    val MPostContent = MutableStateFlow<String>("")
    //发布帖子参数
    val mPublishPostModel:PublishPostRequestModel by lazy{
        PublishPostRequestModel()
    }
    //图片或视频地址
    private val mImgUrls = mutableListOf<ImgItem>()

    /**
     * 发布帖子
     */

    private val publishPostState = MutableStateFlow<UIState>(UIState.Default)
    val publishPostState_ = publishPostState.asStateFlow()
    fun publishPost(){
        mPublishPostModel.content = MPostContent.value //发布内容
        execute(
            action = repository.publishPost(mPublishPostModel),
            onStart = {
                publishPostState.value = UIState.Loading
            },
            onFinished = {
                publishPostState.value = UIState.Success
            },
            onError = {
                publishPostState.value = UIState.Error(it)
            }
        )
    }
    /**
     * 发布帖子：图文发布/视频文字发布
     */
    fun  publishPostWithFiles(files:List<File>,isVideo:Boolean = false){
        //1:上传图片或视频
        execute(
            action = repository.uploadFiles(files),
            onStart = {
                publishPostState.value = UIState.Loading
            },
            onError = {
                publishPostState.value = UIState.Error(it)
            },
            onFinished = {model->
                //2:获得图片网络地址
                if(model.data != null){
                    mImgUrls.clear()
                    mImgUrls.addAll(model.data)
                    Log.d("TAG","图片地址：${mImgUrls.size}")
                    //3.作为参数发布帖子
                    mPublishPostModel.ifVideo = if(isVideo) 1 else 0
                    mPublishPostModel.img = formatImageUrl()
                    publishPost()
                }

            },

        )
    }

    private fun formatImageUrl():String{
        val sb = StringBuilder()
        mImgUrls.forEachIndexed {index,item->
            sb.append(item.url)
            //判断是否为最后一个
            if(index < mImgUrls.size - 1){
                sb.append(",")
            }
        }
        return sb.toString()
    }

}